package com.qualityeclipse.genealogy.parts;

import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.*;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.*;
import org.eclipse.gef.requests.*;

import com.qualityeclipse.genealogy.commands.*;
import com.qualityeclipse.genealogy.figures.NoteFigure;
import com.qualityeclipse.genealogy.model.*;
import com.qualityeclipse.genealogy.model.listener.NoteListener;

/**
 * The {@link EditPart} for the {@link Note} model object. This EditPart is responsible
 * for creating a visual representation for the model object and for updating that visual
 * representation as the model changes.
 */
public class NoteEditPart extends GenealogyElementEditPart 
	implements NoteListener
{
	public NoteEditPart(Note note) {
		setModel(note);
	}

	public Note getModel() {
		return (Note) super.getModel();
	}

	/**
	 * Create and return the figure representing this model object
	 */
	protected IFigure createFigure() {
		return new NoteFigure(getModel().getText());
	}

	/**
	 * Extend the superclass behavior to modify the associated figure's appearance to show
	 * that the element is selected.
	 */
	protected void fireSelectionChanged() {
		((NoteFigure) getFigure()).setSelected(getSelected() != 0);
		super.fireSelectionChanged();
	}

	/**
	 * Create and install {@link EditPolicy} instances used to define behavior
	 * associated with this EditPart's figure.
	 */
	protected void createEditPolicies() {
		// Resize feedback provided by container
		//NonResizableEditPolicy selectionPolicy = new NonResizableEditPolicy();
		//installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, selectionPolicy);

		// Handles deleting the receiver
		installEditPolicy(EditPolicy.COMPONENT_ROLE, new ComponentEditPolicy() {
			protected Command createDeleteCommand(GroupRequest request) {
				NoteContainer container = (NoteContainer) getParent().getModel();
				return new DeleteNoteCommand(container, getModel());
			}
		});
	}
	
	/**
	 * Override the superclass implementation so that the receiver
	 * can add itself as a listener to the underlying model object
	 */
	public void addNotify() {
		super.addNotify();
		getModel().addNoteListener(this);
	}
	
	/**
	 * Override the superclass implementation so that the receiver
	 * can stop listening to events from the underlying model object
	 */
	public void removeNotify() {
		getModel().removeNoteListener(this);
		super.removeNotify();
	}

	// ==================================================================
	// NoteListener

	public void textChanged(String text) {
		((NoteFigure) getFigure()).setText(text);
	}
}
